/*
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.cloud.solutions.autotokenize.testing;


import com.google.common.base.Splitter;
import java.io.Serializable;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/** Matches the JSONPath key, by checking against the array index regex. */
public final class JsonPathArrayPatternMatcher implements Serializable {
  private static final Pattern REGEX_SPECIAL_CHARS =
      Pattern.compile("([\\<\\(\\[\\{\\\\\\^\\-\\=\\$\\!\\|\\]\\}\\)\\?\\*\\+\\.\\>\\\"\\']+)");

  private final String jsonPathArrayPattern;

  public JsonPathArrayPatternMatcher(String jsonPath) {
    this.jsonPathArrayPattern = makePattern(jsonPath);
  }

  public static JsonPathArrayPatternMatcher of(String jsonPath) {
    return new JsonPathArrayPatternMatcher(jsonPath);
  }

  public boolean matches(String value) {
    return value.matches(jsonPathArrayPattern);
  }

  @SuppressWarnings("UnstableApiUsage") // Testing class.
  private static String makePattern(String value) {
    return Splitter.on('.')
            .splitToStream(value)
            .map(part -> REGEX_SPECIAL_CHARS.matcher(part).replaceAll("\\\\$0"))
            .map(part -> part + "(?:\\[\\d+\\])?")
            .collect(Collectors.joining("\\."))
        + "(?:\\.[a-z]+)?$";
  }
}
